<?php

namespace App\Admin\Forms;

use App\Admin\Renderable\LogisticsTable;
use App\Models\Logistic;
use App\Service\SmsService;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;

class OrderDelivery extends Form  implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        // dump($input);

        $id = $this->payload['id'] ?? null;


        if (! $id) {
            return $this->response()->error('参数错误');
        }

        $user = DB::table('order')
                  ->where('order.id',$id)
                  ->join('users','users.id','=','order.user_id')
                  ->first(['users.mobile','users.name','users.id']);
        if (empty($user)){
            return $this->response()->error('订单异常');
        }

        $date = date('Y-m-d H:i:s');
        $result = DB::table('order')
                    ->where('id',$id)
                    ->update([
                        'tracking_number' => $input['tracking_number'],
                        'company_code' => $input['company_code'],
                        'status' => 3,
                        'ship_time' => $date
                    ]);

        $company_name =  DB::table('logistics')->where('company_code',$input['company_code'])->value('company_name');

        DB::table('user_message')->insert([
            'user_id' => $user->id,
            'type' => 2,
            'content' => '尊敬的'.$user->name.'用户，您在校园指数订购的商品已发货，物流运单号：'.$input['tracking_number'].'，物流公司：
'.$company_name.'，请打开微信公众号：校园指数，注意查收！',
            'status' => 2,
            'message_type' => 2,
            'created_at' => $date,
            'updated_at' => $date
        ]);

        SmsService::send('SMS_462295488',$user->mobile,[
            'name' => $user->name,
            'number' => $input['tracking_number'],
            'Inc' => $company_name ?? '物流公司'
        ]);

        return $result ? $this->response()->success('发货成功')->refresh() : $this->response()->error('发货失败');

    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->text('tracking_number','物流单号')->maxLength(50)->required();
        $this->selectTable('company_code','快递公司')
             ->from(LogisticsTable::make())
             ->model(Logistic::class,'company_code','company_name')
             ->required();
    }

    protected function parameters()
    {
        return [

        ];
    }

}
